package com.lalilu.lread.utils

import android.content.Context
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.nio.ByteBuffer
import java.nio.charset.Charset

object StringUtil {
    suspend fun loadAssetToString(context: Context, fileName: String): String =
        withContext(Dispatchers.IO) {
            val inputStream = context.resources.assets.open(fileName)
            val byteArray = ByteArray(inputStream.available())
            inputStream.read(byteArray)
            return@withContext bytesToString(byteArray)
        }

    fun bytesToString(bytes: ByteArray?): String {
        if (bytes == null || bytes.isEmpty()) return ""
        return bytesToString(bytes, Charset.defaultCharset().name())
    }

    fun bytesToString(bytes: ByteArray, charsetString: String): String {
        val charset = Charset.forName(charsetString)
        val buf = ByteBuffer.wrap(bytes)
        val cBuf = charset.decode(buf)
        return cBuf.toString()
    }

    fun getFileNameFromPath(path: String): String {
        val temp = path.split("/")
        return temp[temp.size - 1]
    }

    fun getPathWithoutExt(path: String): String {
        val index = path.lastIndexOf(".")
        return path.slice(IntRange(0, index - 1))
    }

    fun getFileNameFromPathWithoutExt(path: String): String {
        val temp = getFileNameFromPath(path)
        return getPathWithoutExt(temp)
    }

    fun getExtFromText(path: String): String {
        path.lastIndexOf(".")
        val temp = path.split('.')
        return temp[temp.size - 1]
    }

    fun changeExtFromText(text: String, toExt: String): String {
        val temp = getPathWithoutExt(text)
        return "$temp.$toExt"
    }
}